import Redis from 'redis' //Redis驱动
import fastifyPlugin from 'fastify-plugin'
import vconf from '../utils/vconf.js'
const config = vconf('config.yml')

const { sql: { redis = {} } } = config
const redisCli = Redis.createClient(redis.port, redis.host)
redisCli.on('error', (err) => console.log('redis err =>>' + err))

const get_redis = (key) => {
  return new Promise(resolve => redisCli.get(key, (err, reply) => resolve(reply)))
}

const set_redis = (key, value, exprires) => {
  redisCli.set(key, typeof value === 'object' ? JSON.stringify(value) : value)
  //设置过期 单位：秒
  if (exprires) redisCli.expire(key, exprires)
}

async function fpRadis (fastify, opts, done) {
  fastify.decorate('get_redis', get_redis)
  fastify.decorate('set_redis', set_redis)
  done()
}
export default fastifyPlugin(fpRadis)
